<template>
  <div class="business-report">
    <!-- 上部：年份筛选 -->
    <div class="top-bar">
      <div class="title">经营统计报表</div>
      <div class="year-select">
        <el-select v-model="year" placeholder="请选择年份" @change="fetchData">
          <el-option v-for="y in yearOptions" :key="y" :label="y + '年'" :value="y" />
        </el-select>
      </div>
    </div>

    <!-- 中部：统计表格 -->
    <el-table :data="tableRows" border class="report-table" :header-row-class-name="tableHeaderClass">
      <el-table-column v-for="(col, idx) in columns" :key="col.prop" :prop="col.prop" :label="col.label" :min-width="col.minWidth" :class-name="col.className" />
    </el-table>

    <!-- 下部：柱状图 -->
    <div class="chart-box">
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const nowYear = new Date().getFullYear()
const year = ref(nowYear)
const yearOptions = Array.from({length: 6}, (_, i) => nowYear - i)
const reportData = ref([])
const chartRef = ref(null)
let chartInstance = null

const columns = ref([
  { prop: 'item', label: '项目', minWidth: '100', className: 'item-header' },
  // 动态月份列
])

const tableRows = ref([])

const fetchData = async () => {
  try {
    const res = await axios.get(`/carRepair/admin/statisticalStatement/businessReport/${year.value}`)
    if (res.data.code === 200) {
      reportData.value = res.data.data
      buildTable()
      await nextTick()
      renderChart()
    }
  } catch (e) {
    ElMessage.error('获取报表数据失败')
  }
}

const buildTable = () => {
  // 构建表头
  columns.value = [
    { prop: 'item', label: '项目', minWidth: '100', className: 'item-header' },
    ...reportData.value.map(m => ({
      prop: m.month,
      label: m.month,
      minWidth: '80',
      className: ''
    }))
  ]
  // 构建9行数据
  const get = (key) => reportData.value.map(m => m[key])
  tableRows.value = [
    { item: '项目', ...Object.fromEntries(reportData.value.map(m => [m.month, m.month])) },
    { item: '配件销售', ...Object.fromEntries(reportData.value.map(m => [m.month, m.partSaleIncome])) },
    { item: '服务收入', ...Object.fromEntries(reportData.value.map(m => [m.month, m.serviceIncome])) },
    { item: '总收入', ...Object.fromEntries(reportData.value.map(m => [m.month, m.totalIncome])) },
    { item: '配件购买', ...Object.fromEntries(reportData.value.map(m => [m.month, m.partBuyCost])) },
    { item: '工具购买', ...Object.fromEntries(reportData.value.map(m => [m.month, m.toolBuyCost])) },
    { item: '人工成本', ...Object.fromEntries(reportData.value.map(m => [m.month, m.laborCost])) },
    { item: '总成本', ...Object.fromEntries(reportData.value.map(m => [m.month, m.totalCost])) },
    { item: '利润', ...Object.fromEntries(reportData.value.map(m => [m.month, m.profit])) },
  ]
}

const tableHeaderClass = ({ rowIndex }) => {
  // 第1、4、8、9行为浅蓝色
  if ([0, 3, 7, 8].includes(rowIndex)) return 'blue-row'
  return ''
}

const renderChart = () => {
  if (!chartRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  const months = reportData.value.map(m => m.month)
  const totalIncome = reportData.value.map(m => m.totalIncome)
  const totalCost = reportData.value.map(m => m.totalCost)
  const profit = reportData.value.map(m => m.profit)
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['总收入', '总成本', '利润'] },
    xAxis: { type: 'category', data: months },
    yAxis: { type: 'value' },
    series: [
      { name: '总收入', type: 'bar', data: totalIncome, itemStyle: { color: '#409EFF' } },
      { name: '总成本', type: 'bar', data: totalCost, itemStyle: { color: '#67C23A' } },
      { name: '利润', type: 'bar', data: profit, itemStyle: { color: '#E6A23C' } },
    ]
  })
}

onMounted(() => {
  fetchData()
})

watch(year, () => {
  fetchData()
})
</script>

<style scoped>
.business-report {
  padding: 0px;
}
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}
.title {
  font-size: 22px;
  font-weight: bold;
}
.year-select {
  min-width: 120px;
}
.report-table {
  margin-bottom: 30px;
}
.blue-row {
  background: #eaf6ff !important;
  font-weight: bold;
}
.chart-box {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 20px;
}
</style>